package com.cskaoyan.shiro;

import com.cskaoyan.bean.Admin;
import com.cskaoyan.bean.Role;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.PermissionMapper;
import com.cskaoyan.mapper.RoleMapper;
import com.cskaoyan.utils.PermissionApiUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AdminRealm extends AuthorizingRealm {


    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;


    //获取登录信息（验证用户名密码）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        CustomLoginToken token = (CustomLoginToken) authenticationToken;

        String username = token.getUsername();

        //查询数据库中的密码
        Admin admin = new Admin();
        admin.setUsername(username);
        Admin res = adminMapper.selectAdminByUsername(admin);
        String password = res.getPassword();

        return new SimpleAuthenticationInfo(username, password, this.getName());
    }


    //获取授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String username = (String) principalCollection.getPrimaryPrincipal();

        //查询这个比的角色和权限
        Admin admin = new Admin();
        admin.setUsername(username);
        Admin res = adminMapper.selectAdminByUsername(admin);

        Integer[] roleIds = res.getRoleIds();

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        ArrayList<String> permissions = new ArrayList<>();

        for (Integer roleId : roleIds) {

            //查询每个角色name
            Role role = this.roleMapper.selectByPrimaryKey(roleId);

            //放进去
            simpleAuthorizationInfo.addRole(role.getName());

            //查询每个角色对应的权限
            List<Integer> permission = permissionMapper.selectRolePermission(roleId);
            for (Integer permissionId : permission) {
                String s = permissionMapper.selectPermissionAPIById(permissionId);
                String api = PermissionApiUtils.dealApiSwitch(s);

                permissions.add(api);
            }
        }

        simpleAuthorizationInfo.addStringPermissions(permissions);

        return simpleAuthorizationInfo;
    }
}



















